//
//  FLOAuthViewController.swift
//  swift_learning
//
//  Created by aron on 2017/2/1.
//  Copyright © 2017年 arons. All rights reserved.
//

import UIKit
import SVProgressHUD

class FLOAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // navigationbar
        loadNavBar()
        
        // 加载页面
        loadPage()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func loadNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(FLOAuthViewController.onCancel))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(FLOAuthViewController.onFill))

        navigationItem.title = "授权"
    }
    
    
    /// 取消
    @objc private func onCancel() {
        dismiss(animated: true, completion: nil)
    }
    
    
    /// 填充
    @objc private func onFill() {
        // 1.书写js代码 : javascript / java --> 雷锋和雷峰塔
        let jsCode = "document.getElementById('userId').value='\(PrivateConstants.weiboAccount)';document.getElementById('passwd').value='\(PrivateConstants.weiboPassWd)';"
        
        // 2.执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
    
    private func loadPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=677530225&redirect_uri=http://www.baidu.com"
        guard let url = URL(string: urlString) else {
            return
        }
        let request : URLRequest = URLRequest(url: url)
        webView.delegate = self
        webView.loadRequest(request)
    }
}

// MARK: - ......::::::: UIWebViewDelegate :::::::......
extension FLOAuthViewController : UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取Code
        let urlString = request.url?.absoluteString ?? ""
        if (urlString as NSString).contains("code=") {
            let range = (urlString as NSString).range(of: "code=", options: .caseInsensitive)
            let location = range.location + range.length
            let code = (urlString as NSString).substring(from: location)
            
            NetworkTools.sharedInstance.requestAccessToken(code: code, finished: { (account : UserAccount?, error : Error?) in
                if error != nil || account == nil{
                    // 错误提示
                    SVProgressHUD.showError(withStatus: "错误，请重试")
                }else {
                    // 加载用户信息
                    self.loadUserInfo(acc: account!);
                }
            })
            return false
        }
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        // 加载框
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // 隐藏加载框
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        // 隐藏加载框
        SVProgressHUD.dismiss()
    }
}


// MARK: - ......::::::: 网络请求 :::::::......
extension FLOAuthViewController {
    func loadUserInfo(acc: UserAccount) {
        NetworkTools.sharedInstance.requestUserInfo(acc: acc, finished: { (account : UserAccount?, error : Error?) in
            if error != nil || account == nil{
                // 错误提示
                SVProgressHUD.showError(withStatus: "错误，请重试")
            }else {
                // 保存数据
                UserAccountManager.sharedInstance.saveAccount(account: account!)
                
                // 退出当前页面
                self.dismiss(animated: false, completion: {
                    // 设置rootViewController为欢迎页
                    UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
                })
            }
        })
    }
}
